package com.xhu.collegestudentrentalsystem.module.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xhu.collegestudentrentalsystem.module.user.dao.HouseDAO;
import com.xhu.collegestudentrentalsystem.module.user.dao.HouseOrderDAO;
import com.xhu.collegestudentrentalsystem.module.user.entity.House;
import com.xhu.collegestudentrentalsystem.module.user.entity.HouseOrder;
import com.xhu.collegestudentrentalsystem.module.user.entity.Page;
import com.xhu.collegestudentrentalsystem.module.user.entity.dto.HouseDTO;
import com.xhu.collegestudentrentalsystem.module.user.service.IHouseService;
import com.xhu.collegestudentrentalsystem.util.constant.EntityProperty;
import com.xhu.collegestudentrentalsystem.util.constant.EnumProperty;
import com.xhu.collegestudentrentalsystem.util.constant.StatusMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhu huilin
 * @date 2023/3/5 19:21
 */
@Service
public class HouseServiceImpl implements IHouseService {

    @Autowired
    private HouseDAO houseDAO;

    @Autowired
    private HouseOrderDAO houseOrderDAO;

    /**
     * 发布房源信息，等待管理员审核
     * @param house 房屋实体类对象
     * @return
     */
    @Override
    public Long addHouse(House house) {
        // 使用mybatis-plus，自动填充主键返回值
        int i = houseDAO.insert(house);
        if(i > 0) {
            return house.getId();
        }
        return new Long(i);
    }

    /**
     * 查询数据库中是否有以审核通过或待审核的相同的房产证号
     *      已审核通过的房产证号不可重复；true表示有，false表示没有
     * @param certificateNo
     * @return
     */
    @Override
    public Boolean isHouseExist(String certificateNo) {
        Integer[] status = new Integer[]{0, 1, -1, -2};
        House house =
                houseDAO.selectOne(new QueryWrapper<House>()
                        .eq(EntityProperty.house.CERTIFICATE_NO, certificateNo)
                        .in(EntityProperty.house.HOUSE_STATUS, status));

        if(house == null){
            return false;
        }
        return true;
    }

    /**
     * 根据房东id查询当前房东发布的所有房源信息
     *      房东自己删除的不显示
     */
    public List<House> findHousesByUserId(Long userId, Page page){
        // 开启分页
        PageHelper.startPage(page.getCurrent() , page.getLimit());
        QueryWrapper<House> qw = new QueryWrapper<House>().eq(EntityProperty.house.USER_ID, userId).ne(EntityProperty.house.HOUSE_STATUS, StatusMsg.houseStatus.OWNER_DELETE);
        // 分页后的数据
        List<House> houses = houseDAO.selectList(qw);
        // 数据库中查询总数据量
        Integer count = houseDAO.selectCount(qw);
        page.setRows(count);
        return houses;
    }

    /**
     * 根据id查询一条房屋信息记录
     */
    @Override
    public House findHouseById(Long houseId) {
        House house =
                houseDAO.selectOne(new QueryWrapper<House>()
                        .eq(EntityProperty.ID, houseId)
                        .ne(EntityProperty.house.HOUSE_STATUS, StatusMsg.houseStatus.OWNER_DELETE));

        return house;
    }

    /**
     * 修改房屋信息
     */
    @Override
    public Integer updateHouseInfo(House house) {
        if(house.getSlideUrl() == null || "".equals(house.getSlideUrl())){
            return houseDAO.updateInfo(house);
        }else {
            return houseDAO.updateInfoAndPic(house);
        }
    }

    /**
     * 根据房子的id修改该房子的状态
     *      0-未出租；1-已出租；-1已下架；-2待审核；-3审核不通过；-4房东删除
     * @param houseId 房屋id，前端传入
     * @param status  房屋状态，控制器中定义
     * @return
     */
    @Override
    public Integer updateHouseStatus(Long houseId, Integer status) {
        return houseDAO.updateHouseStatus(houseId, status);
    }

    /**
     * 查询当前房子的租住情况，只需要查询状态为待付款和已出租的情况，其它视为未出租
     * @param houseId   房子id
     * @return
     */
    @Override
    public List<HouseOrder> findHouseOrderByHouseId(Long houseId) {
        List<HouseOrder> orders =
                houseOrderDAO.selectList(new QueryWrapper<HouseOrder>()
                        .eq(EntityProperty.order.HOUSE_ID, houseId).in(EntityProperty.STATUS, new Integer[]{-1, 0}));
        return orders;
    }

    /**
     * 查询当前房子租住人数
     */
    @Override
    public Integer findHouseOrderUserCount(Long houseId) {
        return houseOrderDAO.findHouseOrderUserNum(houseId);
    }

    /**
     * 查询当前已通过审核的房子信息，根据状态、时间排序，未出租的、最新的排在前列
     */
    @Override
    public List<House> findHouseNew() {
        return houseDAO.findHouseOrderByStatusAndParam("create_time");
    }

    /**
     * 根据条件查询房子信息
     *      houseDTO包含：房子所处城市、小区、出租类型、价格范围。
     *      page：用于分页。
     */
    @Override
    public List<House> searchHouses(HouseDTO houseDTO, Page page) {
        // 分页
        PageHelper.startPage(page.getCurrent() , page.getLimit());
        // 查询房子信息
        QueryWrapper<House> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(EntityProperty.STATUS, new Integer[]{StatusMsg.houseStatus.UN_RENT, StatusMsg.houseStatus.HAS_RENT});
        if(houseDTO.getCity() != null && !EnumProperty.EMPTY_STRING.equals(houseDTO.getCity())){
            queryWrapper.eq(EntityProperty.house.CITY, houseDTO.getCity());
        }
        if(houseDTO.getAddress() != null && !EnumProperty.EMPTY_STRING.equals(houseDTO.getAddress())){
            queryWrapper.like(EntityProperty.house.ADDRESS, houseDTO.getAddress());
        }
        if(houseDTO.getRentType() != null && !EnumProperty.STRING_NONE.equals(houseDTO.getRentType()) && !EnumProperty.EMPTY_STRING.equals(houseDTO.getRentType())){
            queryWrapper.eq(EntityProperty.house.RENT_TYPE, houseDTO.getRentType());
        }
        if(houseDTO.getPriceRange() != null && !EnumProperty.EMPTY_STRING.equals(houseDTO.getPriceRange())){
            queryWrapper.between(EntityProperty.house.MONTH_RENT, houseDTO.getMinPrice(), houseDTO.getMaxPrice());
        }
        if(houseDTO.getAreaRange() != null && !EnumProperty.EMPTY_STRING.equals(houseDTO.getAreaRange())){
            queryWrapper.between(EntityProperty.house.AREA, houseDTO.getMinArea(), houseDTO.getMaxArea());
        }
        List<House> houses = houseDAO.searchHousesByDto(queryWrapper, houseDTO.getOrderType());
        // 获取总数据数量（只有传入的查询条件会影响查询总数量）
        Integer count = houseDAO.selectCount(queryWrapper);
        page.setRows(count);
        return houses;
    }

    /**
     * 查询高分房子信息（未出租的）
     */
    @Override
    public List<House> findHouseHighScore() {
        return houseDAO.findHouseOrderByStatusAndParam("score");
    }
}
